﻿using System;
using System.Data;
using System.Data.Common;

//自定义命名空间
using DreamCube.Framework.DataAccess.Basic;
using DreamCube.Framework.DataAccess.Sqlserver;
using DreamCube.Foundation.Basic.Objects.Log;

namespace PicServer.DAL
{
    /// <summary>
    /// 获取数据库的基本信息
    /// </summary>
    public static class DatabaseDetails
    {
        #region "字段"

        /// <summary>
        /// 判断是否连接上数据库
        /// </summary>
        private static Boolean isConnected;

        #endregion

        #region "属性"

        /// <summary>
        /// 标识数据库是否连接成功
        /// </summary>
        public static Boolean IsConnected
        {
            get { return isConnected; }
        }

        /// <summary>
        /// 数据库版本号
        /// </summary>
        public static String DbVersion
        {
            get;
            private set;
        }

        /// <summary>
        /// 标识数据库是否已经进行了初始化
        /// </summary>
        public static Boolean HasInitial
        {
            get;
            private set;
        }

        /// <summary>
        /// 数据库创建时间，返回格式为：yyyy-MM-dd HH:mm:ss
        /// </summary>
        public static String CreateTime
        {
            get;
            private set;
        }

        #endregion

        #region "公共方法"

        /// <summary>
        /// 传入索引表数据，初始化数据库
        /// </summary>
        /// <param name="tableCount"></param>
        public static void InitialDB(Int32 tableCount = 255)
        {
            if (tableCount <= 0 || tableCount > 255)
                throw new ArgumentException("索引表的数据必须在0-255之间");

            //创建数据库版本号的表
            String dbVersionSql = " if (object_id(N'DatabaseDetails',N'U') is null)"
                                    + "BEGIN "
                                    + "CREATE TABLE DatabaseDetails("
                                    + "dbversion VARCHAR(255),"
                                    + "hasInitial Bit, "
                                    + "createTime datetime default(getdate()) "
                                    + ");"
                                    + "INSERT INTO DatabaseDetails(dbversion,hasInitial)"
                                    + "VALUES('1.0',0);end;";

            //创建每一个表对应的大文件的序号的信息表
            String fileTableFileIndexCreateSql =
                                        "CREATE TABLE FileTableFileIndex("
                                        + "id INT IDENTITY(1,1) PRIMARY KEY,"
                                        + "tableName VARCHAR(100),"
                                        + "fileIndex INT);";
            String insertTableFileIndex = "insert into FileTableFileIndex(tableName,fileIndex) Values('FileTable{0}',{1})";
            String sqlText = "CREATE TABLE FileTable{0}"
                             + "(id int identity(1,1) primary key,"
                             + "fileName VARCHAR(1000),"
                             + "fileStartIndex float,"
                             + "fileDataLength int, "
                             + "fileDes nvarchar(2000) default '', "
                             + "insertTime datetime default(getdate()));";
            String updateSql = "update DatabaseDetails set hasInitial=1";
            Database db = DbManager.GetDBByName();
            using (DbConnection conn = db.CreateConnection(true))
            {
                DbTransaction trans = conn.BeginTransaction();
                try
                {
                    db.ExecuteNonQuery(db.GetSqlStringCommand(dbVersionSql), trans);
                    db.ExecuteNonQuery(db.GetSqlStringCommand(fileTableFileIndexCreateSql), trans);
                    //创建255个索引表
                    for (Int32 i = 0; i < tableCount; i++)
                    {
                        db.ExecuteNonQuery(db.GetSqlStringCommand(String.Format(sqlText, i)), trans);
                        db.ExecuteNonQuery(db.GetSqlStringCommand(String.Format(insertTableFileIndex, i, 0)), trans);
                    }
                    db.ExecuteNonQuery(db.GetSqlStringCommand(updateSql), trans);
                    trans.Commit();
                    //初始化完毕之后重新连接数据库
                    ConnectDB();
                }
                catch (Exception ex)
                {
                    LoggerManager.Logger.MakeLogAsync(ex);
                    trans.Rollback();
                }
            }
        }

        #endregion

        #region "私有方法"

        static DatabaseDetails()
        {
            //构造此类型的时候读取数据库
            ConnectDB();
        }

        /// <summary>
        /// 执行连接数据库方法
        /// </summary>
        private static void ConnectDB()
        {
            isConnected = false;
            try
            {
                Database db = DbManager.GetDBByName();
                String sqlText = "select dbversion,hasInitial,createTime from DatabaseDetails";
                using (IDataReader reader = db.ExecuteReader(CommandType.Text, sqlText))
                {
                    if (reader.Read())
                    {
                        isConnected = true;
                        DbVersion = reader.GetString(0);
                        HasInitial = reader.GetBoolean(1);
                        CreateTime = reader.GetDateTime(2).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
            }
            catch (Exception ex)
            {
                isConnected = false;
                LoggerManager.Logger.MakeLogAsync(ex);
            }
        }

        #endregion
    }
}
